"""
崩溃恢复模块 - 防止程序闪退后无限重启
"""

import os
import json
import time
import logging
from datetime import datetime, timedelta


class CrashRecovery:
    """崩溃恢复管理器"""
    
    def __init__(self, crash_file="crash_history.json"):
        self.crash_file = crash_file
        self.logger = logging.getLogger('crash_recovery')
        self.max_crashes = 3  # 最大崩溃次数
        self.time_window = 300  # 时间窗口（秒）
        
    def check_crash_history(self):
        """检查崩溃历史，决定是否允许启动"""
        if not os.path.exists(self.crash_file):
            return True
            
        try:
            with open(self.crash_file, 'r') as f:
                crash_data = json.load(f)
                
            # 清理过期的崩溃记录
            current_time = time.time()
            crash_times = [t for t in crash_data.get('crash_times', []) 
                          if current_time - t < self.time_window]
            
            # 检查是否超过崩溃限制
            if len(crash_times) >= self.max_crashes:
                self.logger.error(f"在{self.time_window}秒内崩溃{len(crash_times)}次，拒绝启动")
                return False
                
            # 更新崩溃记录
            crash_times.append(current_time)
            crash_data['crash_times'] = crash_times
            crash_data['last_crash'] = datetime.now().isoformat()
            
            with open(self.crash_file, 'w') as f:
                json.dump(crash_data, f)
                
            return True
            
        except Exception as e:
            self.logger.error(f"读取崩溃历史失败: {e}")
            return True
            
    def record_successful_start(self):
        """记录成功启动，清除崩溃历史"""
        try:
            if os.path.exists(self.crash_file):
                os.remove(self.crash_file)
            self.logger.info("成功启动，清除崩溃历史")
        except Exception as e:
            self.logger.error(f"清除崩溃历史失败: {e}")
            
    def get_crash_info(self):
        """获取崩溃信息用于显示"""
        if not os.path.exists(self.crash_file):
            return None
            
        try:
            with open(self.crash_file, 'r') as f:
                crash_data = json.load(f)
                
            current_time = time.time()
            crash_times = [t for t in crash_data.get('crash_times', []) 
                          if current_time - t < self.time_window]
                          
            if crash_times:
                return {
                    'crash_count': len(crash_times),
                    'time_window': self.time_window,
                    'last_crash': crash_data.get('last_crash', 'Unknown'),
                    'can_retry_in': self.time_window - (current_time - min(crash_times))
                }
        except:
            pass
            
        return None


def safe_compare_decorator(func):
    """安全比对装饰器，捕获异常并记录"""
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except MemoryError as e:
            logging.error(f"内存不足错误: {e}")
            # 记录内存不足错误但不计入崩溃
            raise Exception("内存不足，请关闭其他程序或减少数据量后重试")
        except Exception as e:
            logging.error(f"比对过程中发生错误: {e}")
            # 记录其他错误
            raise
    return wrapper 